/*
 * Copyright (c) 2020 pig4cloud Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.pig4cloud.pig.ads.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.pig4cloud.pig.admin.api.entity.SysDictItem;
import com.pig4cloud.pig.ads.clickhouse3399.mapper.ConvertTargetMapper;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.ads.service.SelectListService;
import com.pig4cloud.pig.ads.service.TtCustomAudienceService;
import com.pig4cloud.pig.api.entity.AdIndustry;
import com.pig4cloud.pig.api.util.JsonUtil;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.constant.enums.PlatformTypeEnum;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.api.dto.CustomAudienceDto;
import com.pig4cloud.pig.api.entity.AppIdWithPackName;
import com.pig4cloud.pig.api.entity.TtCustomAudience;
import com.pig4cloud.pig.ads.main3399.mapper.AppIdMapper;
import com.pig4cloud.pig.ads.service.*;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @author john
 * @ 广告账户 前端控制器
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/select_list")
@Api(value = "select_list", tags = "下拉框列表")
public class SelectListController {

	private final AdvService advService;

	private final AppIdMapper appIdMapper;


	private final SelectListService selectListService;

	private final TtCustomAudienceService ttCustomAudienceService;

	private final TtAccesstokenService ttAccesstokenService;


	private final ConvertTargetMapper convertTargetMapper;

	private final AdIndustryService adIndustryService;

	@GetMapping("/ad_accounts")
	public R select4AdAccounts(String searchStr) {
		return R.ok(advService.options4AdAccounts(searchStr));
	}

	@RequestMapping("/appid_list")
	public R test01(Integer platformId) {
		List<AppIdWithPackName> appIdList = appIdMapper.appIdList(platformId);
		return R.ok(appIdList);
	}

	/**
	 * @param dto
	 * @return
	 * @头条自定义人群包
	 */
	@RequestMapping("/custom_audience_list")
	public R customAudienceList(CustomAudienceDto dto) {
		//return customAudienceService.customAudienceList(dto);

		List<TtCustomAudience> list = new ArrayList<>();


		List<String> adList = advService.getOwnerAdv(SecurityUtils.getUser().getId(), PlatformTypeEnum.TT.getValue());
		if (adList == null || adList.size() == 0) {
			return R.ok(list);
		}

		//设置where条件
		QueryWrapper<TtCustomAudience> queryWrapper = new QueryWrapper<>();
		if (StringUtils.isNotBlank(dto.getAdvertiserId())) {
			queryWrapper.in("account_id", dto.getAdvertiserId());
		}

		//人群包名称或id
		if (StringUtils.isNotBlank(dto.getCustomAudienceId())) {
			queryWrapper.and(wrapper -> wrapper.like("custom_audience_id", dto.getCustomAudienceId()).or().like("name", dto.getCustomAudienceId()));
		}


		queryWrapper.in("account_id", adList);
		queryWrapper.eq("delivery_status", "CUSTOM_AUDIENCE_DELIVERY_STATUS_AVAILABLE");

		queryWrapper.orderByDesc("create_time").orderByAsc("custom_audience_id");

		QueryWrapper<TtCustomAudience> btjQueryWrapper = queryWrapper.clone();

		queryWrapper.and(wrapper -> wrapper.eq("tag", "系统推荐"));

		//推荐
		List<TtCustomAudience> tjlist = ttCustomAudienceService.list(queryWrapper);

		//不包含推荐的内容
		btjQueryWrapper.and(wrapper -> wrapper.ne("tag", "系统推荐"));
		List<TtCustomAudience> btjlist = ttCustomAudienceService.list(btjQueryWrapper);

		tjlist.addAll(btjlist);

		return R.ok(tjlist);
	}

	@RequestMapping("/make_data_district")
	public R makeDataDistrict(CustomAudienceDto dto) {
		//toutiaoDistrictService.listByParentId(1);
		return null;
/*		toutiaoDistrictService.makeDataDistrict();
		return null;*/
	}

	@RequestMapping("/make_data_district_business")
	public R makeDataDistrictBusiness(CustomAudienceDto dto) {
/*		toutiaoDistrictService.makeDataDistrictBusiness();
		return null;*/
		return null;
	}


	@RequestMapping("/cz_site")
	public R czSite(String advertiserId, Integer current, Integer size) {
		return selectListService.czSite(advertiserId, current, size);
	}

	@RequestMapping("/action_text_list")
	public R actionTextList(String advertiserId, String landingType) {
		return selectListService.actionTextList(advertiserId, landingType);
	}

	@RequestMapping("/call_2action_list")
	public R callToActionList(String advertiserId, String recommendType, String advancedCreativeType) {
		return selectListService.callToActionList(advertiserId, recommendType, advancedCreativeType);
	}

	@RequestMapping("/industry_list")
	public R industryList(String advertiserId) throws JsonProcessingException {
		//return selectListService.industryList(advertiserId);
		String result=JsonUtil.toUnderlineJSONStringValue(adIndustryService.selectAdIndustryResAll(new QueryWrapper<AdIndustry>()));
		return R.ok(JSONObject.parseArray(result));
	}

	/**
	 * 查询投放人，   根据自己的角色取并集
	 *
	 * @return
	 */
	@ApiOperation("查询所属角色的投放人")
	@RequestMapping("/getServingList")
	public R getChannelList(String gname) {
		PigUser pigxUser = SecurityUtils.getUser();
		List<String> roleIdList = pigxUser.getAuthorities()
				.stream().map(GrantedAuthority::getAuthority)
				.filter(authority -> authority.startsWith(SecurityConstants.ROLE))
				.map(authority -> authority.split(StrUtil.UNDERLINE)[1])
				.collect(Collectors.toList());
		//根据角色获取账号列表
		return R.ok();
	}


	/**
	 * 获取广告转化目标，深度转化木模板
	 *
	 * @return
	 */
	@GetMapping("/getConvertList")
	public R getConvertList() {
		// 转换目标字典表查询（转化目标，深度转化目标）
		Map<String, Object> param = new HashMap<>();
		List<SysDictItem> sysDictItemList = convertTargetMapper.selectConvertTarget(param);
		return R.ok(sysDictItemList);
	}

	/**
	 * 获取 token 提高给运营服务用
	 */
	@Inner
	@PostMapping("/getToken")
	public R getToken(@RequestBody String adAccount) {
		String accessToken = ttAccesstokenService.fetchAccesstoken(adAccount);
		return R.ok(accessToken);
	}
}
